<?php
// 本类由系统自动生成，仅供测试用途
namespace Api\Controller;
use Think\Controller;
class ShoppingController extends PublicController {

    /**
     * 获取购物车列表
     * @author tiedong
     * @date 2018-01-18
     */
	public function index(){
        $shopping=M("shopping_char");
        $product=M("product");
        $brand_model=M("brand");
        $product_model=M("brand_image");
		$user_id = $this->get("id");
		if (!$user_id) {
			$this->json_error("请登录！");
			exit();
		}

        /*$shop = $shopping->where(''.$qz.'shopping_char.uid='.intval($user_id))->join('left join __SHANGCHANG__ on __SHANGCHANG__.id = __SHOPPING_CHAR__.shop_id')->distinct(''.$qz.'shopping_char.shop_id')->field(''.$qz.'shangchang.id,'.$qz.'shangchang.name,'.$qz.'shangchang.logo')->select();
		foreach ($shop as $n=>$v){
			$shop[$n]['logo'] = __DATAURL__.$v['logo'];
        	$shop[$n]['slist']=$shopping->where(''.$qz.'shopping_char.uid='.intval($user_id).' and '.$qz.'shopping_char.shop_id='.intval($v['id']))->join('LEFT JOIN __PRODUCT__ ON __SHOPPING_CHAR__.pid = __PRODUCT__.id')->field(''.$qz.'shopping_char.id,'.$qz.'product.id as proid,'.$qz.'product.name,'.$qz.'product.num as pnum,'.$qz.'product.price_yh,'.$qz.'product.photo_x,'.$qz.'shopping_char.num,'.$qz.'shopping_char.buff,'.$qz.'shopping_char.price')->select();
			//获取产品规格名称
			foreach ($shop[$n]['slist'] as $k=>$vl){
        		$key=explode(',', $vl['buff']);
        		foreach ($key as $m=>$val){
        			$buff_text=M('guige')->where('id='.intval($val))->getField('name');
        			$shop[$n]['slist'][$k]['g_name'] .= '&nbsp;'.$buff_text;
        		}

        		$shop[$n]['slist'][$k]['photo_x'] = __DATAURL__.$vl['photo_x'];
        	}
		}*/

		$cart = $shopping->where('uid='.intval($user_id))->field('id,uid,pids,price,num,shop_id,gid')->select();
        foreach ($cart as $k => $v) {
            $cart[$k]['name'] = $brand_model->where("id=".$v['shop_id'])->getField("name");
            $cart[$k]['brand_image'] =__DATAURL__."UploadFiles/".$product_model->where("id=".$v['gid'])->getField("brand_photo");
            $pids = explode(",",$v['pids']);
            $proArr = array();
            foreach ( $pids as $key=>$value ) {
                $pid = explode("_",$value);
                $pro_info = $product->where('id='.intval($pid[0]))->field('name,price')->find();
                $pro_info['num'] = $pid[1];
                array_push($proArr,$pro_info);
            }
            $cart[$k]['product'] = $proArr;

        }
        $this->json_result($cart);
		exit();
    }

    /**
     * 购物车商品的删除
     * @author tiedong
     * @date 2018-01-19
     */
	public function delete(){
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status'=>0,'err'=>'网络异常，请稍后再试.'));
            exit();
        }
		$shopping=M("shopping_char");
        $cart_id=trim($_GET['cart_id'],',');
        if (!$cart_id) {
            echo json_encode(array('status'=>0,'err'=>'网络错误，请稍后再试.'));
            exit();
        }
        $res = $shopping->where('id in ('.$cart_id.') AND uid='.intval($uid))->delete(); // 删除
		if($res){
			$this->json_result("删除成功");
			exit();
		}else{
			$this->json_error("删除失败");
			exit();
		}
	}

	//***************************
	//  会员修改购物车数量接口
	//***************************
	public function up_cart(){
		$shopping=M("shopping_char");
		$uid = intval($_REQUEST['user_id']);
		$cart_id = intval($_REQUEST['cart_id']);
		$num=intval($_REQUEST['num']);

		if (!$uid || !$cart_id || !$num) {
			echo json_encode(array('status'=>0,'err'=>'网络异常.'.__LINE__));
			exit();
		}

		$check = $shopping->where('id='.intval($cart_id))->find();
		if (!$check) {
			echo json_encode(array('status'=>0,'err'=>'购物车信息错误！'));
			exit();
		}

		//检测库存
		$pro_num = M('product')->where('id='.intval($check['pid']))->getField('num');
		if($num>intval($pro_num)){
			echo json_encode(array('status'=>0,'err'=>'库存不足！'));
			exit();
		}
		
		$data=array();
		$data['num']=$num;

		$res = $shopping->where('id ='.intval($cart_id).' AND uid='.intval($uid))->save($data);
		if ($res) {
			echo json_encode(array('status'=>1,'succ'=>'操作成功!'));
			exit();
		}else{
			echo json_encode(array('status'=>0,'err'=>'操作失败.'));
			exit();
		}
		
	}

    /**
     * 购物车多个删除
     */
	public function qdelete(){
		$uid = intval($this->get("id"));
		if (!$uid) {
			echo json_encode(array('status'=>0,'err'=>'网络异常，请稍后再试.'));
			exit();
		}
		$shopping=M("shopping_char");
		$cart_id=trim($_GET['cart_id'],',');
		if (!$cart_id) {
			echo json_encode(array('status'=>0,'err'=>'网络错误，请稍后再试.'));
			exit();
		}

	    $res = $shopping->where('id in ('.$cart_id.') AND uid='.intval($uid))->delete(); // 删除
		if($res){
			echo json_encode(array('status'=>1));
			exit();
		}else{
			echo json_encode(array('status'=>0,'err'=>'操作失败.'));
			exit();
		}
	}


    /**
     * 添加到购物车
     * @author tiedong
     * @date 2018-01-18
     */
	public function add(){
		$uid = $this->get("id");
		if (!$uid) {
            $this->json_error("登录状态异常");
			exit();
		}
        $brand_id = isset($_GET['brand_id'])?intval($_GET['brand_id']) : 0 ;//心意卡
        $bi_id    = isset($_GET['brand_image_id'])?intval($_GET['brand_image_id']) : 0 ;//卡面id
		$num      = isset($_GET['num'])?intval($_GET['num']) : 0 ;//总数量
        $price    = isset($_GET['price'])?$_GET['price'] : 0 ;//总价格
		if (!intval($num)) {
			$this->json_error("参数错误");
			exit();
		}
        $pids_arr = isset($_GET['pids']) ? $_GET['pids'] : 0;
        //$pids_arr = "278_4,279_4";
        $pids = explode(",",$pids_arr);
        foreach ( $pids as $value ) {
            $pid = explode("_",$value);
            //检查商品是否已经下架或者不存在！
            $check = $this->check_cart(intval($pid[0]));
            if ($check['status']==0) {
                $this->json_error($check['err']);
                exit;
            }
            //检查商品的库存
            $check = $this->check_num(intval($pid[0]),intval($pid[1]));
            if ($check['status']==0) {
                $this->json_error($check['err']);
                exit;
            }
        }
		$shpp=M("shopping_char");
		$data = array();
        $data['pids']           = $pids_arr;
        $data['num']            = intval($num);
        $data['addtime']        = time();
        $data['uid']            = intval($uid);
        $data['type']           = 1;
        $data['buff']           = 1;
        $data['price']          = $price;
        $data['shop_id']        = $brand_id;
        $data['gid']            = $bi_id;
        $res=$shpp->data($data)->add($data);
		if($res){
		    $returnArr = array(
		        'id' =>$res,
                'msg'=> "加入购物车成功"
            );
            $this->json_result($returnArr);//该商品已成功加入您的购物车
			exit;
		}else{
			$this->json_error("加入失败");
			exit;
		}
	}


	//***************************
	//  会员立即购买下单接口
	//***************************
	public function check_shop(){
		$cart_id = trim($_REQUEST['cart_id'],',');
		$id=explode(',',$cart_id);
		if (!$cart_id) {
			echo json_encode(array('status'=>0));
			exit();
		}

		foreach ($id as $k=>$v){
			$shoop[$k]=M("shopping_char")->where('id ='.intval($v))->field('shop_id,pid')->find();
        }

		foreach($shoop as $key => $value){
			$result[$key] = M("product")->where('id='.intval($value['pid']))->field('id,price,price_yh')->select();
			$price[] = i_array_column($result[$key], 'price_yh');
		}
		//dump($price);exit;
		foreach($price as $keys => $va){
			$str .= implode(",", $va).",";
		}
		$str = trim($str, ",");
		$parr = explode(",", $str);
		if(array_sum($parr) && in_array("0", $parr)){
			echo json_encode(array('status'=>0));
			exit();
		}
		
		$names = i_array_column($shoop, 'shop_id');
		
		$arr=array_unique($names);
		$val= sizeof($arr);
		if($val=='1'){
			echo json_encode(array('status'=>1));
			exit();
		}else{
			echo json_encode(array('status'=>2));
			exit();
		}	 
	}


    /*
       去除HTNL标签
    */
    public function html_entity($array){
    	foreach ($array as $key => $value) {
        	$array[$key]['content'] = strip_tags(html_entity_decode($value['content']));
        }
        return $array;
    }

}